import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:客户端（UDP编程）
 * User: 87111
 * Date: 2025-11-16
 * Time: 16:33
 */
public class UdpEchoClient {
    //用来发送数据报的
    private DatagramSocket socket = null;

    //UDP本身不存储服务器的目的IP的目的端口
    private String serverIp;
    private int serverPort;

    //此处的构造方法要指定访问的服务器的地址
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //客户端使用随机端口号
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        while(true) {
            //1. 从控制台读取用户输入的内容
            System.out.println("请输入要发送的内容：");
            //判断发送的内容是否为空
            if (!sc.hasNext()) {
                break;
            }
            String request = sc.next();
            //2. 把请求发送给服务器，此时要构造DatagramPacket对象
            //不仅要构造载荷，还要设置服务器的IP和端口
            DatagramPacket requestSocket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            //3. 发送数据报
            socket.send(requestSocket);
            //4. 接收服务器的响应
            DatagramPacket responseSocket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responseSocket);
            //5. 将服务器读取到的数据进行解析，打印出来
            String response = new String(responseSocket.getData(), 0, responseSocket.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
